import os
import time

import pymysql
import yaml
from cryptography.fernet import Fernet
from openai import OpenAI
from pymysql.cursors import DictCursor

from wxauto import WeChat

# 正式上线需要修改这个密码
YML_PATH = "conf/application.yml"
# 加密密码
KEY = b'kc7aV67sn-Cmb0_qak5E1lJoDjxRJbdP4c0UL8XGjPc='

# 读取yml 配置文件
def read_yaml(filename: str = YML_PATH):
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    with open(filename, "r", encoding="utf-8") as f:
        return yaml.safe_load(f.read())


# 对称数据解密
def decrypt_data(data):
    if data is None or data == '':
        return ""
    # 使用秘钥创建一个Fernet对象
    cipher_suite = Fernet(KEY)
    decrypted = cipher_suite.decrypt(data.encode('utf-8')).decode('utf-8')
    return decrypted

# 读取ftp mysql 等配置文件
config = read_yaml(YML_PATH)

# 连接mysql 数据源
ldxt99_druid = config["druid"]["ldxt99"]
# 解密数据库密码
passwd = decrypt_data(ldxt99_druid["passwd"])
ldxt99_db = pymysql.connect(
    host=ldxt99_druid["host"],
    port=ldxt99_druid["port"],
    user=ldxt99_druid["user"],
    passwd=passwd,
    database=ldxt99_druid["database"]
)
ldxt99_db_cursor = ldxt99_db.cursor(cursor=DictCursor)

# 查询机构和群名对照表
sql = "select distinct qunm from jg_qunm_ys"
ldxt99_db_cursor.execute(sql)
listen_list = ldxt99_db_cursor.fetchall()

wx = WeChat()

for listen_obj in listen_list:
    wx.AddListenChat(who=listen_obj['qunm'])  # 添加监听对象

client = OpenAI(api_key="sk-8635b3e35b5543ad918a712e34518b4b", base_url="https://api.deepseek.com")

# 持续监听消息，有消息则对接大模型进行回复
wait = 1  # 设置1秒查看一次是否有新消息
while True:
    msgs = wx.GetListenMessage()
    for chat in msgs:
        msg = msgs.get(chat)  # 获取消息内容
        for m in msg:
            if m.type == 'friend' and '龙龙' in m.content:
                # ===================================================
                # 处理消息逻辑
                print("开始时间：" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                print("问题内容：" + m.content)
                response = client.chat.completions.create(
                    model="deepseek-chat",
                    # model="deepseek-reasoner",
                    messages=[
                        {"role": "user", "content": m.content[3: len(m.content)]}
                    ],
                    stream=False
                )
                reply = "@" + m[0] + " " + response.choices[0].message.content
                print("结束时间: " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

                # ===================================================

                # 回复消息
                chat.SendMsg(reply)  # 回复
    time.sleep(wait)

